import React, { useState, useRef } from 'react';
import { Form, Input, Button, Select, Tabs, message, Checkbox } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, MobileOutlined, SafetyOutlined, ReloadOutlined } from '@ant-design/icons';
import { useNavigate, Link } from 'react-router-dom';
import Vcode from 'react-vcode';
import './Register.scss';

const { Option } = Select;

interface EmailRegisterForm {
  username: string;
  email: string;
  password: string;
  confirmPassword: string;
  captcha: string;
  agree: boolean;
}

interface PhoneRegisterForm {
  username: string;
  phone: string;
  code: string;
  password: string;
  confirmPassword: string;
  agree: boolean;
}

const Register: React.FC = () => {
  const navigate = useNavigate();
  const [emailForm] = Form.useForm<EmailRegisterForm>();
  const [phoneForm] = Form.useForm<PhoneRegisterForm>();
  const [loading, setLoading] = useState(false);
  const [registerType, setRegisterType] = useState<'email' | 'phone'>('email');
  const [captchaCode, setCaptchaCode] = useState('');
  const [countdown, setCountdown] = useState(0);
  const vcodeRef = useRef<any>(null);

  // 邮箱注册
  const handleEmailRegister = async (values: EmailRegisterForm) => {
    if (!values.agree) {
      message.warning('请阅读并同意用户协议和隐私政策');
      return;
    }

    setLoading(true);
    try {
      // TODO: 调用邮箱注册接口
      // const response = await registerByEmail(values);
      
      // 模拟注册
      setTimeout(() => {
        message.success('注册成功！请登录');
        navigate('/login');
      }, 1000);
    } catch (error) {
      message.error('注册失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 手机号注册
  const handlePhoneRegister = async (values: PhoneRegisterForm) => {
    if (!values.agree) {
      message.warning('请阅读并同意用户协议和隐私政策');
      return;
    }

    setLoading(true);
    try {
      // TODO: 调用手机号注册接口
      message.success('注册成功！请登录');
      navigate('/login');
    } catch (error) {
      message.error('注册失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 发送验证码
  const handleSendCode = async () => {
    const phone = phoneForm.getFieldValue('phone');
    if (!phone) {
      message.error('请输入手机号');
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      message.error('请输入正确的手机号');
      return;
    }

    // TODO: 调用发送验证码接口
    message.success('验证码已发送');
    
    // 倒计时
    let count = 60;
    setCountdown(count);
    const timer = setInterval(() => {
      count--;
      setCountdown(count);
      if (count === 0) {
        clearInterval(timer);
      }
    }, 1000);
  };

  // 刷新图片验证码
  const handleRefreshCaptcha = () => {
    if (vcodeRef.current) {
      vcodeRef.current.onClick();
    }
  };

  // 验证码改变
  const handleCaptchaChange = (code: string) => {
    setCaptchaCode(code);
  };

  const tabItems = [
    {
      key: 'email',
      label: '邮箱注册',
      children: (
        <Form
          form={emailForm}
          name="email-register"
          onFinish={handleEmailRegister}
          autoComplete="off"
          size="large"
          scrollToFirstError
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, max: 20, message: '用户名长度为3-20个字符' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入用户名（3-20个字符）"
            />
          </Form.Item>

          <Form.Item
            name="email"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input
              prefix={<MailOutlined />}
              placeholder="请输入邮箱"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, max: 20, message: '密码长度为6-20个字符' },
              { 
                pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, 
                message: '密码必须包含大小写字母和数字' 
              }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码（6-20个字符）"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请再次输入密码"
            />
          </Form.Item>

          <Form.Item
            name="captcha"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 4, message: '验证码为4位' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || value.toLowerCase() === captchaCode.toLowerCase()) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('验证码错误'));
                },
              }),
            ]}
          >
            <div className="captcha-input-wrapper">
              <Input
                prefix={<SafetyOutlined />}
                placeholder="请输入验证码"
                maxLength={4}
              />
              <div className="vcode-wrapper">
                <Vcode
                  ref={vcodeRef}
                  onChange={handleCaptchaChange}
                  width={120}
                  height={40}
                  length={4}
                />
                <Button
                  icon={<ReloadOutlined />}
                  onClick={handleRefreshCaptcha}
                  className="refresh-btn"
                  size="small"
                  title="刷新验证码"
                />
              </div>
            </div>
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value ? Promise.resolve() : Promise.reject(new Error('请阅读并同意协议')),
              },
            ]}
          >
            <Checkbox>
              我已阅读并同意
              <Link to="/terms" target="_blank"> 用户协议 </Link>
              和
              <Link to="/privacy" target="_blank"> 隐私政策</Link>
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              注册
            </Button>
          </Form.Item>
        </Form>
      ),
    },
    {
      key: 'phone',
      label: '手机注册',
      children: (
        <Form
          form={phoneForm}
          name="phone-register"
          onFinish={handlePhoneRegister}
          autoComplete="off"
          size="large"
          scrollToFirstError
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, max: 20, message: '用户名长度为3-20个字符' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入用户名（3-20个字符）"
            />
          </Form.Item>

          <Form.Item
            name="phone"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input
              prefix={<MobileOutlined />}
              placeholder="请输入手机号"
            />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '验证码为6位数字' }
            ]}
          >
            <div className="code-input-wrapper">
              <Input
                placeholder="请输入验证码"
                maxLength={6}
              />
              <Button
                onClick={handleSendCode}
                disabled={countdown > 0}
              >
                {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
              </Button>
            </div>
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, max: 20, message: '密码长度为6-20个字符' },
              { 
                pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, 
                message: '密码必须包含大小写字母和数字' 
              }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码（6-20个字符）"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请再次输入密码"
            />
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value ? Promise.resolve() : Promise.reject(new Error('请阅读并同意协议')),
              },
            ]}
          >
            <Checkbox>
              我已阅读并同意
              <Link to="/terms" target="_blank"> 用户协议 </Link>
              和
              <Link to="/privacy" target="_blank"> 隐私政策</Link>
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              注册
            </Button>
          </Form.Item>
        </Form>
      ),
    },
  ];

  return (
    <div className="register-container">
      <div className="register-background">
        <div className="bg-overlay"></div>
      </div>
      
      <div className="register-content">
        <div className="register-card">
          <div className="register-header">
            <h1>创建账号</h1>
            <p>加入 XYQ 校园平台</p>
          </div>

          <Tabs
            activeKey={registerType}
            onChange={(key) => setRegisterType(key as 'email' | 'phone')}
            items={tabItems}
            centered
          />

          <div className="register-footer">
            <span>已有账号？</span>
            <Link to="/login" className="login-link">
              立即登录
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Register;

